package com.some;

import com.review.backpack_01.BP01;

public class BP01_test {
    //01背包问题
    //每件物品只能选0次或者1次
    private static int maxValue(int[] weight, int[] value, int bagWeight) {//常规做法

        int[][] dp = new int[weight.length][bagWeight + 1];
        // 因为dp[0][j]中的0对应的是第一件物品，所以dp[0][j]的含义是可选物品为1，背包容量为j；
        // 当j大于等于weight[0]此时背包最大价值就是value[0]也就是第一件物品的价值
        for (int j = bagWeight; j >= weight[0]; j--) {
            dp[0][j] = value[0];
        }

        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[0].length; j++) {
                if (weight[i] > j) {
                    dp[i][j] = dp[i - 1][j];
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
                }
            }
        }
        for (int[] ints : dp) {
            for (int anInt : ints) {
                System.out.print(anInt + " \t");
            }
            System.out.println();
        }
        return dp[dp.length - 1][dp[0].length - 1];
    }

    private static int maxValue_2(int[] weight, int[] value, int bagWeight) {//常规做法
        int[] dp = new int[bagWeight + 1];

        for (int i = 0; i < weight.length; i++) {
            for (int j = bagWeight; j >= weight[i]; j--) {
                dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]);
            }
        }
        return dp[dp.length - 1];
    }

    public static void main(String[] args) {
        System.out.println("使用二维数组：" + maxValue(new int[]{1, 3, 4}, new int[]{15, 20, 30}, 4));
        System.out.println("改进做法，使用一维数组：" + maxValue_2(new int[]{1, 3, 4}, new int[]{15, 20, 30}, 4));

    }
}
